#ifndef MQTT_CLIENT_H
#define MQTT_CLIENT_H

#include <mqtt/async_client.h>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <atomic>
#include <string>
#include <vector>

const std::string SERVER_ADDRESS("tcp://101.132.85.231:1883");
const std::string CLIENT_ID("mqtt_multi_thread_client");
const int QOS = 1;

// 消息结构体，用于存储待发布的消息
struct Message {
    std::string topic;
    std::string payload;
};

// MQTT客户端类，继承自mqtt::callback以处理异步事件
class MqttClient : public mqtt::callback {
private:
    mqtt::async_client client_;
    mqtt::connect_options connOpts_;
    
    // 消息队列相关
    std::queue<Message> messageQueue_;
    std::mutex queueMutex_;
    std::condition_variable queueCondVar_;
    std::atomic<bool> running_;
    
    // 线程
    std::thread publishThread_;
    
    // 订阅的主题列表
    std::vector<std::string> topics_;

public:
    MqttClient(const std::vector<std::string>& topics);
    ~MqttClient();
    
    // 启动客户端
    void start();
    
    // 停止客户端
    void stop();
    
    // 向队列中添加消息以进行发布
    void enqueueMessage(const std::string& topic, const std::string& payload);
    
    // 处理接收到的消息（由回调函数调用）
    virtual void handleMessage(const std::string& topic, const std::string& payload);

private:
    // 发布线程的主循环
    void publishLoop();
    
    // 实现mqtt::callback接口的回调函数
    void message_arrived(mqtt::const_message_ptr msg) override;
    void connection_lost(const std::string& cause) override;
    void delivery_complete(mqtt::delivery_token_ptr token) override;
};

#endif // MQTT_CLIENT_H